package 极客算法训练营.chapter07;

import java.util.Arrays;

public class 从前序与中序遍历序列构造二叉树 {

        public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            if (preorder.length == 0 && inorder.length == 0) {
                return null;
            }
            //子集中先序遍历的初始元素为当前子树的根节点
            TreeNode root = new TreeNode(preorder[0]);
            for (int i = 0; i < inorder.length; i++) {
                //找到中序遍历中的对应元素，其左边为左子树集，右边为右子树集
                if (inorder[i] == preorder[0]) {
                    int[] pre_left = Arrays.copyOfRange(preorder, 1, i + 1);
                    int[] pre_right = Arrays.copyOfRange(preorder, i + 1, preorder.length);
                    int[] in_left = Arrays.copyOfRange(inorder, 0, i);
                    int[] in_right = Arrays.copyOfRange(inorder, i + 1, inorder.length);
                    root.left = buildTree(pre_left, in_left);
                    root.right = buildTree(pre_right, in_right);
                    break;
                }
            }
            return root;
        }
    }
}
